<template>
  <div class="coach-profile">
    <el-row :gutter="20">
      <!-- 左侧栏 -->
      <el-col :span="16">
        <!-- 信息编辑卡片 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <span>信息编辑</span>
            </div>
          </template>

          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-form
                :model="profileForm"
                :rules="profileRules"
                ref="profileFormRef"
                label-width="100px"
              >
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="profileForm.name" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="profileForm.gender">
                    <el-radio label="MALE">男</el-radio>
                    <el-radio label="FEMALE">女</el-radio>
                    <el-radio label="OTHER">其他</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker
                    v-model="profileForm.birthday"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="身份证号" prop="idNumber">
                  <el-input v-model="profileForm.idNumber" />
                </el-form-item>
                <el-form-item label="通讯地址" prop="address">
                  <el-input
                    v-model="profileForm.address"
                    type="textarea"
                    :rows="3"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitProfileForm" :loading="savingProfile">
                    保存修改
                  </el-button>
                  <el-button @click="resetProfileForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="修改密码" name="password">
              <el-form
                :model="passwordForm"
                :rules="passwordRules"
                ref="passwordFormRef"
                label-width="100px"
              >
                <el-form-item label="当前密码" prop="currentPassword">
                  <el-input
                    v-model="passwordForm.currentPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="passwordForm.newPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitPasswordForm" :loading="changingPassword">
                    修改密码
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="教学信息" name="teaching">
              <el-form
                :model="teachingForm"
                :rules="teachingRules"
                ref="teachingFormRef"
                label-width="100px"
              >
                <el-form-item label="教练证号" prop="licenseNumber">
                  <el-input v-model="teachingForm.licenseNumber" />
                </el-form-item>
                <el-form-item label="入职日期" prop="hireDate">
                  <el-date-picker
                    v-model="teachingForm.hireDate"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="教学经验" prop="yearsOfExperience">
                  <el-input-number
                    v-model="teachingForm.yearsOfExperience"
                    :min="0"
                    :max="50"
                    controls-position="right"
                    style="width: 120px;"
                  />
                  <span style="margin-left: 5px; font-size: 14px;">年</span>
                </el-form-item>
                <el-form-item label="专长领域" prop="specialization">
                  <el-select
                    v-model="teachingForm.specialization"
                    placeholder="请选择专长领域"
                    style="width: 100%"
                    filterable
                    allow-create
                    default-first-option
                  >
                    <el-option label="小型车驾驶" value="小型车驾驶" />
                    <el-option label="大型车驾驶" value="大型车驾驶" />
                    <el-option label="摩托车驾驶" value="摩托车驾驶" />
                    <el-option label="安全驾驶" value="安全驾驶" />
                    <el-option label="驾驶理论" value="驾驶理论" />
                  </el-select>
                </el-form-item>
                <el-form-item label="个人简介" prop="bio">
                  <el-input
                    v-model="teachingForm.bio"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入您的个人简介，包括教学理念、特色等"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitTeachingForm" :loading="savingTeaching">
                    保存修改
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="偏好设置" name="preferences">
              <el-form
                :model="preferencesForm"
                ref="preferencesFormRef"
                label-width="120px"
              >
                <el-form-item label="通知设置">
                  <el-checkbox-group v-model="preferencesForm.notifications">
                    <el-checkbox label="email">邮件通知</el-checkbox>
                    <el-checkbox label="sms">短信通知</el-checkbox>
                    <el-checkbox label="system">系统通知</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item label="工作时间">
                  <el-table :data="preferencesForm.workingHours" style="width: 100%">
                    <el-table-column prop="day" label="星期" width="100">
                      <template #default="scope">
                        {{ getDayName(scope.row.day) }}
                      </template>
                    </el-table-column>
                    <el-table-column label="工作时间">
                      <template #default="scope">
                        <el-time-picker
                          v-model="scope.row.start"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder="开始时间"
                          style="width: 120px"
                        />
                        <span style="margin: 0 10px">-</span>
                        <el-time-picker
                          v-model="scope.row.end"
                          format="HH:mm"
                          value-format="HH:mm"
                          placeholder="结束时间"
                          style="width: 120px"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>

                <el-form-item label="最大预约数">
                  <el-slider
                    v-model="preferencesForm.maxAppointments"
                    :min="1"
                    :max="20"
                    show-input
                    style="width: 300px"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="submitPreferencesForm" :loading="savingPreferences">
                    保存设置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>

        <!-- 教学统计卡片 -->
        <el-card class="stats-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>教学统计</span>
            </div>
          </template>

          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value">{{ teachingStats.students }}</div>
              <div class="stat-label">当前学员</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ teachingStats.appointments }}</div>
              <div class="stat-label">总预约数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ teachingStats.completed }}</div>
              <div class="stat-label">已完成</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ teachingStats.rating }}分</div>
              <div class="stat-label">平均评分</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧栏 -->
      <el-col :span="8">
        <!-- 个人信息卡片 -->
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" size="small" @click="handleEditAvatar">
                更换头像
              </el-button>
            </div>
          </template>

          <div class="avatar-container">
            <el-avatar :size="120" :src="coachInfo.avatar || defaultAvatar" />
            <h3>{{ coachInfo.name }}</h3>
            <p class="coach-id">教练ID: {{ coachInfo.id }}</p>

            <el-divider />

            <el-descriptions :column="1">
              <el-descriptions-item label="入职日期">
                {{ coachInfo.hireDate }}
              </el-descriptions-item>
              <el-descriptions-item label="手机号码">
                {{ coachInfo.phone }}
                <el-button type="text" @click="handleChangePhone">
                  修改
                </el-button>
              </el-descriptions-item>
              <el-descriptions-item label="电子邮箱">
                {{ coachInfo.email || '未设置' }}
                <el-button type="text" @click="handleChangeEmail">
                  {{ coachInfo.email ? '修改' : '添加' }}
                </el-button>
              </el-descriptions-item>
              <el-descriptions-item label="教学经验">
                {{ coachInfo.yearsOfExperience }}年
              </el-descriptions-item>
              <el-descriptions-item label="专长领域">
                {{ coachInfo.specialization || '未设置' }}
              </el-descriptions-item>
              <el-descriptions-item label="评分">
                <el-rate
                  v-model="coachInfo.rating"
                  disabled
                  show-score
                  score-template="{value}分"
                  :max="5"
                />
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改手机号对话框 -->
    <el-dialog v-model="phoneDialogVisible" title="修改手机号" width="400px">
      <el-form
        :model="phoneForm"
        :rules="phoneRules"
        ref="phoneFormRef"
        label-width="80px"
      >
        <el-form-item label="新手机号" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入新手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="phoneDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPhoneForm" :loading="updatingPhone">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改邮箱对话框 -->
    <el-dialog v-model="emailDialogVisible" title="修改邮箱" width="400px">
      <el-form
        :model="emailForm"
        :rules="emailRules"
        ref="emailFormRef"
        label-width="80px"
      >
        <el-form-item label="新邮箱" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入新邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="emailDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEmailForm" :loading="updatingEmail">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import requestUtil from "@/util/request";
// 导入默认头像图片
import defaultAvatar from '@/assets/Mihu.png'

// 教练信息
const coachInfo = ref({
  id: '',
  name: '',
  avatar: '',
  phone: '',
  email: '',
  hireDate: '',
  yearsOfExperience: 0,
  specialization: '',
  rating: 0
})

// 教学统计数据
const teachingStats = ref({
  students: 0,
  appointments: 0,
  completed: 0,
  rating: 0
})

// 标签页
const activeTab = ref('basic')

// 表单加载状态
const savingProfile = ref(false)
const changingPassword = ref(false)
const savingTeaching = ref(false)
const savingPreferences = ref(false)
const updatingPhone = ref(false)
const updatingEmail = ref(false)

// 基本信息表单
const profileForm = ref({
  name: '',
  gender: '',
  birthday: '',
  idNumber: '',
  address: ''
})

const profileRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ]
}

const profileFormRef = ref(null)

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 5) {
    callback(new Error('密码长度不能少于5位'))
  } else {
    if (passwordForm.value.confirmPassword !== '') {
      if (passwordFormRef.value) {
        passwordFormRef.value.validateField('confirmPassword')
      }
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const passwordRules = {
  currentPassword: [
    {required: true, message: '请输入当前密码', trigger: 'blur'}
  ],
  newPassword: [
    {validator: validatePass, trigger: 'blur'}
  ],
  confirmPassword: [
    {validator: validatePass2, trigger: 'blur'}
  ]
}

const passwordFormRef = ref(null)

// 教学信息表单
const teachingForm = ref({
  licenseNumber: '',
  hireDate: '',
  yearsOfExperience: 0,
  specialization: '',
  bio: ''
})

const teachingRules = {
  licenseNumber: [{required: true, message: '请输入教练证号', trigger: 'blur'}],
  hireDate: [{required: true, message: '请选择入职日期', trigger: 'change'}],
  yearsOfExperience: [{required: true, message: '请输入教学经验', trigger: 'change'}]
}

const teachingFormRef = ref(null)

// 偏好设置表单
const preferencesForm = ref({
  notifications: ['email', 'system'],
  workingHours: [
    { day: 1, start: '08:00', end: '18:00' },
    { day: 2, start: '08:00', end: '18:00' },
    { day: 3, start: '08:00', end: '18:00' },
    { day: 4, start: '08:00', end: '18:00' },
    { day: 5, start: '08:00', end: '18:00'},
    {day: 6, start: '09:00', end: '17:00'},
    {day: 0, start: '09:00', end: '17:00'}
  ],
  maxAppointments: 10
})

const preferencesFormRef = ref(null)

// 手机号表单
const phoneForm = ref({
  phone: ''
})

const phoneRules = {
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ]
}

const phoneFormRef = ref(null)

// 邮箱表单
const emailForm = ref({
  email: ''
})

const emailRules = {
  email: [
    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ]
}

const emailFormRef = ref(null)

// 对话框显示控制
const phoneDialogVisible = ref(false)
const emailDialogVisible = ref(false)

// 获取星期名称
const getDayName = (day) => {
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return days[day]
}

// 获取教练信息
const fetchCoachInfo = async () => {
  try {
    // 从localStorage获取用户ID
    const userId = localStorage.getItem('user_id')

    if (!userId) {
      ElMessage.error('用户未登录或会话已过期')
      return
    }

    // 通过userId获取教练id
    const coachIdResponse = await requestUtil.get(`/coach/msg/userId/${userId}`)
    const coachId = coachIdResponse.data.data.coach_id

    // 获取用户信息表中的信息
    const response1 = await requestUtil.get(`/profile/msg/${userId}`)
    const data1 = response1.data

    // 获取教练信息表中的信息
    const response2 = await requestUtil.get(`/coach/msg/${coachId}`)
    const data2 = response2.data.data
    // console.log(data2)
    // 获取用户表中的信息
    const response3 = await requestUtil.get(`/user/secret/msg/${userId}`)
    const data3 = response3.data.data[0]

    // 获取教学统计数据
    await fetchTeachingStats(userId, coachId)

     // 获取教练评分
    const coachRating = await fetchCoachRating(coachId)

    // 更新教练信息
    coachInfo.value = {
      id: data2.coach_id || data1.user_id,
      name: data1.fullname || '',
      avatar: defaultAvatar,
      phone: data3.phone || '',
      email: data3.email || '',
      hireDate: data2.hire_date || data3.create_at || '',
      yearsOfExperience: Number(data2.years_of_experience) || 0,
      specialization: data2.specialization || '',
      rating: coachRating
    }

    // 初始化表单数据
    profileForm.value = {
      name: data1.fullname || '',
      gender: data1.gender || '',
      birthday: data1.birthday || '',
      idNumber: data1.id_number || '',
      address: data1.address || ''
    }

    teachingForm.value = {
      licenseNumber: data2.license_number || '',
      hireDate: data2.hire_date || '',
      yearsOfExperience: data2.years_of_experience || 0,
      specialization: data2.specialization || '',
      bio: data2.bio || ''
    }
  } catch (error) {
    ElMessage.error('获取教练信息失败: ' + (error.message || '未知错误'))
    console.error('获取教练信息失败:', error)
  }
}

// 获取教学统计数据
const fetchTeachingStats = async (userId, coachId) => {
  try {
    // 获取学员数量
    const studentsResponse = await requestUtil.get(`/student/msg`)
    const studentsCount = studentsResponse.data.total || 0

    // 获取预约数量
    const appointmentsResponse = await requestUtil.get(`/appointment/msg/coach/${userId}`)
    let totalApps = 0
    let completedApps = 0

    if (appointmentsResponse.data && appointmentsResponse.data.data) {
      const appointments = appointmentsResponse.data.data
      totalApps = appointments.total || 0

      if (appointments.data && Array.isArray(appointments.data)) {
        completedApps = appointments.data.filter(app => app.status === 'COMPLETED').length
      }
    }
    // 获取教练评分
    const coachRating = await fetchCoachRating(coachId)

    teachingStats.value = {
      students: studentsCount,
      appointments: totalApps,
      completed: completedApps,
      rating: coachRating
    }
  } catch (error) {
    console.warn('获取教学统计数据失败:', error)
  }
}

// 获取教练平均评分的通用函数
const fetchCoachRating = async (coachId) => {
  try {
    const trainingResponse = await requestUtil.get('/student_training/trainings')
    if (trainingResponse.data && trainingResponse.data.data) {
      const trainings = trainingResponse.data.data
      // 筛选该教练的训练记录
      const coachTrainings = trainings.filter(training => training.coach_id == coachId)

      let totalRating = 0
      let ratingCount = 0
      coachTrainings.forEach(training => {
        if (training.rating && training.rating > 0) {
          totalRating += training.rating
          ratingCount++
        }
      })

      const avgRating = ratingCount > 0 ? (totalRating / ratingCount) : 0
      return parseFloat(avgRating.toFixed(1))
    }
  } catch (trainingError) {
    console.warn('获取教练评分失败:', trainingError)
  }
  return 0
}


// 提交基本信息
const submitProfileForm = () => {
  if (!profileFormRef.value) return

  profileFormRef.value.validate(async (valid) => {
    if (valid) {
      savingProfile.value = true
      try {
        // 从localStorage获取用户ID
        const userId = localStorage.getItem('user_id')

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期')
          savingProfile.value = false
          return
        }

        // 调用API保存数据
        await requestUtil.put(`/profile/update/${userId}`, {
          fullname: profileForm.value.name,
          gender: profileForm.value.gender,
          birthday: profileForm.value.birthday,
          id_number: profileForm.value.idNumber,
          address: profileForm.value.address
        })

        coachInfo.value.name = profileForm.value.name
        ElMessage.success('个人信息更新成功')

        // 显示通知
        ElNotification({
          title: '成功',
          message: '个人信息已更新',
          type: 'success'
        })
      } catch (error) {
        ElMessage.error('更新失败: ' + (error.message || '未知错误'))
        console.error('更新个人信息失败:', error)
      } finally {
        savingProfile.value = false
      }
    }
  })
}

// 重置基本信息表单
const resetProfileForm = () => {
  if (profileFormRef.value) {
    profileFormRef.value.resetFields()
  }
}

// 提交密码修改
const submitPasswordForm = () => {
  if (!passwordFormRef.value) return

  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      changingPassword.value = true
      try {
        // 从localStorage获取用户ID
        const userId = localStorage.getItem('user_id')

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期')
          changingPassword.value = false
          return
        }

        // 获取用户当前信息
        const userResponse = await requestUtil.get(`/user/secret/msg/${userId}`)
        const userData = userResponse.data.data[0]

        // 验证当前密码是否正确
        if (passwordForm.value.currentPassword !== userData.password) {
          ElMessage.error('当前密码不正确')
          changingPassword.value = false
          return
        }

        if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
          ElMessage.error('新密码和确认密码不一致')
          changingPassword.value = false
          return
        }

        // 调用API修改密码
        await requestUtil.put(`/user/update/${userId}`, {
          password: passwordForm.value.newPassword
        })

        ElMessage.success('密码修改成功')
        ElNotification({
          title: '安全提醒',
          message: '密码已成功修改，请妥善保管',
          type: 'success'
        })

        passwordForm.value = {
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
      } catch (error) {
        ElMessage.error('密码修改失败: ' + (error.message || '未知错误'))
        console.error('密码修改失败:', error)
      } finally {
        changingPassword.value = false
      }
    }
  })
}

// 提交教学信息
const submitTeachingForm = () => {
  if (!teachingFormRef.value) return

  teachingFormRef.value.validate(async (valid) => {
    if (valid) {
      savingTeaching.value = true
      try {
        // 获取当前用户 ID
        const userId = localStorage.getItem('user_id')
        if (!userId) {
          ElMessage.error('用户未登录或会话已过期')
          savingTeaching.value = false
          return
        }

        // 通过 userId 获取 coach_id
        const coachIdResponse = await requestUtil.get(`/coach/msg/userId/${userId}`)
        const coachId = coachIdResponse.data.data.coach_id

        // 发送 PATCH 请求，只传需要更新的字段
        await requestUtil.patch(`/coach/update/${coachId}`, {
          license_number: teachingForm.value.licenseNumber,
          hire_date: teachingForm.value.hireDate,
          years_of_experience: Number(teachingForm.value.yearsOfExperience),
          specialization: teachingForm.value.specialization,
          bio: teachingForm.value.bio
        })

        // 更新本地显示
        coachInfo.value.hireDate = teachingForm.value.hireDate
        coachInfo.value.yearsOfExperience = teachingForm.value.yearsOfExperience
        coachInfo.value.specialization = teachingForm.value.specialization

        ElMessage.success('教学信息更新成功')
        ElNotification({
          title: '成功',
          message: '教学信息已更新',
          type: 'success'
        })
      } catch (error) {
        ElMessage.error('更新失败: ' + (error.message || '未知错误'))
        console.error('更新教学信息失败:', error)
      } finally {
        savingTeaching.value = false
      }
    }
  })
}

// 提交偏好设置
const submitPreferencesForm = () => {
  savingPreferences.value = true
  try {
    // 这里应该调用API保存偏好设置
    console.log('保存偏好设置:', preferencesForm.value)

    ElMessage.success('偏好设置保存成功')
    ElNotification({
      title: '成功',
      message: '偏好设置已保存',
      type: 'success'
    })
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
    console.error('保存偏好设置失败:', error)
  } finally {
    savingPreferences.value = false
  }
}

// 编辑头像
const handleEditAvatar = () => {
  ElMessage.info('修改头像功能开发中')
}

// 修改手机号
const handleChangePhone = () => {
  phoneForm.value.phone = coachInfo.value.phone
  phoneDialogVisible.value = true
}

// 修改邮箱
const handleChangeEmail = () => {
  emailForm.value.email = coachInfo.value.email
  emailDialogVisible.value = true
}

// 提交手机号修改
const submitPhoneForm = () => {
  if (!phoneFormRef.value) return

  phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      updatingPhone.value = true
      try {
        // 从localStorage获取用户ID
        const userId = localStorage.getItem('user_id')

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期')
          updatingPhone.value = false
          phoneDialogVisible.value = false
          return
        }

        // 调用API修改手机号
        await requestUtil.put(`/user/update/${userId}`, {
          phone: phoneForm.value.phone
        })

        // 更新本地显示
        coachInfo.value.phone = phoneForm.value.phone
        phoneDialogVisible.value = false
        ElMessage.success('手机号修改成功')
        ElNotification({
          title: '成功',
          message: '手机号已更新',
          type: 'success'
        })
      } catch (error) {
        ElMessage.error('手机号修改失败: ' + (error.message || '未知错误'))
        console.error('手机号修改失败:', error)
      } finally {
        updatingPhone.value = false
      }
    }
  })
}

// 提交邮箱修改
const submitEmailForm = () => {
  if (!emailFormRef.value) return

  emailFormRef.value.validate(async (valid) => {
    if (valid) {
      updatingEmail.value = true
      try {
        // 从localStorage获取用户ID
        const userId = localStorage.getItem('user_id')

        if (!userId) {
          ElMessage.error('用户未登录或会话已过期')
          updatingEmail.value = false
          emailDialogVisible.value = false
          return
        }

        // 调用API修改邮箱
        await requestUtil.put(`/user/update/${userId}`, {
          email: emailForm.value.email
        })

        // 更新本地显示
        coachInfo.value.email = emailForm.value.email
        emailDialogVisible.value = false
        ElMessage.success('邮箱修改成功')
        ElNotification({
          title: '成功',
          message: '邮箱已更新',
          type: 'success'
        })
      } catch (error) {
        ElMessage.error('邮箱修改失败: ' + (error.message || '未知错误'))
        console.error('邮箱修改失败:', error)
      } finally {
        updatingEmail.value = false
      }
    }
  })
}

// 组件挂载时获取教练信息
onMounted(() => {
  fetchCoachInfo()
})
</script>

<style scoped>
.coach-profile {
  padding: 20px;
}

.profile-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-container {
  text-align: center;
  padding: 10px;
}

.avatar-container h3 {
  margin: 15px 0 5px;
}

.coach-id {
  margin: 0;
  color: #999;
  font-size: 14px;
}

/* 教学统计样式 */
.stats-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  padding: 10px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 表单样式 */
.el-input-number {
  width: 120px !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-row {
    flex-direction: column;
  }

  .el-col {
    width: 100%;
    margin-bottom: 20px;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
